package com.fafa.myreflect2;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Parameter;

public class MyReflectDemo {
    @Test
    public void test() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        //获取字节码文件对象
        Class<?> clazz = Class.forName("com.fafa.myreflect2.Student");
        //获取构造方法
        /*
        Constructor<?>[] cons = clazz.getConstructors();

        for (Constructor<?> con : cons) {
            System.out.println(con);
        }
         */

        /*
        Constructor<?>[] con2 = clazz.getDeclaredConstructors();
        for (Constructor<?> constructor : con2) {
            System.out.println(constructor);
        }
         */
        Constructor<?> con1 = clazz.getDeclaredConstructor();
        System.out.println(con1);

        Constructor<?> con2 = clazz.getDeclaredConstructor(String.class);
        System.out.println(con2);

        Constructor<?> con3 = clazz.getDeclaredConstructor(String.class,int.class);
        System.out.println(con3);


        //获取权限修饰符
        int modifiers = con3.getModifiers();
        System.out.println(modifiers);

        //获取形参
        for (Parameter parameter : con3.getParameters()) {
            System.out.println(parameter);
        }

        //暴力反射：临时取消权限校验
        con3.setAccessible(true);
        //使用私有方法创建对象
        Student stu = (Student)con3.newInstance("张三", 23);

    }


}
